package bit.lotterysystem.service.impl;

import bit.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import bit.lotterysystem.common.exception.ServiceException;
import bit.lotterysystem.service.PictureService;


import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File dir=new File(localPath);
        if(!dir.exists()){
            dir.mkdirs();//可以直接创建多级目录

        }
        //创建索引
        //aaa.jpj->xxx.jpg
          String filename = multipartFile.getOriginalFilename();
         assert filename != null;
         String suffix = filename.substring(filename.lastIndexOf("."));
         filename= UUID.randomUUID()+suffix;//UUID:生成唯一的识别码

        //图片保存
        try {
            multipartFile.transferTo(new File(localPath+"/"+filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }
        return filename;
    }
}
